import React, { Component } from "react";
import CardList from "./components/CardList/CardList";
import SearchBox from "./components/SearchBox/SearchBox";
import "./App.scss";

class App extends Component {
  state = {
    monsters: [],
    searchField: "",
  };

  handleChange = (e) => {
    this.setState({ searchField: e.target.value });
  }

  async componentDidMount() {
    // Fetch call
    // fetch("https://jsonplaceholder.typicode.com/users")
    //   .then((response) => response.json())
    //   .then((users) => this.setState({ monsters: users }))
    //   .catch(error => console.log(error));

    // Async / await call
    try {
      const usersResponse = await fetch(
        "https://jsonplaceholder.typicode.com/users"
      );
      const users = await usersResponse.json();
      this.setState({ monsters: users });
    } catch (error) {
      console.log("Произошла ошибка!");
    }
  }

  render() {
    const { monsters, searchField } = this.state;
    const filteredMonsters = monsters.filter((monster) => {
      return monster.name.toLowerCase().includes(searchField.toLowerCase());
    });

    return (
      <div className="App">
        <h1>Monsters Rolodex</h1>
        <SearchBox
          handleChange={this.handleChange}
          placeholder="search robots"
        />
        <CardList monsters={filteredMonsters} />
      </div>
    );
  }
}

export default App;
